const app = getApp();
import Toast from '../miniprogram_npm/@vant/weapp/toast/toast';
import Base64 from './Base64.js';
import CommonService from './service/commonService.js';

//token登录
function tokenLogin(inputObj,fromRepair,reportForm,reportSend,errorData,errorInside) {
  Toast.loading({
    duration: 0,
    forbidClick: true,
    message: '登录中...'
  });

  //用于审核，不走接口
  if(inputObj.userName=='account' && inputObj.password=='123456'){
    app.globalData.userInfo = {
      id: 363,
      depart: 585,
      departObj:[{
        name: "智能电子工牌",
        type: 4
      }],
      userName: "account",
      dataAuthorityOfUser:{
        depart: [639, 585, 959, 1802, 3563, 3565]
      },
      roles:[{"_id":"5ec247d2c863502744bcb6b8","id":9,"appId":[2,3,5],"dataAuthority":{"depart":[1,1],"type":[1,2,3,4,7]},"uiAuthOfRole":{"iot_tianjun":{"menuid":[""],"menu":{"equipmentList":{"list":{},"analysis":{}}}},"iot_admin":{"menuid":[93,79,88,80,83,96,97,122,124,126,125,153,154],"menu":{"equipment":{"base":{},"brandType":true,"memberType":true},"equipmentList":{"list":{},"analysis":{}},"baseInformation":{"SetEquipmentType":true,"SetEquipmentModel":true,"SetMountingsInformation":true},"OfficialAccountMaterial":{"VideoManagement":true},"systemManager":{"depart":{}}}},"iot_weapp":{"menu":{"iot":{"repairRecord":{"state":true,"callRecord":true,"revoke":true},"reportForm":true,"equipmentGroup":{"projectCount":true},"equipmentList":{"directPowerCheck":true,"directRecovery":true,"overhaul":true,"repair":true,"charge":true,"directStaticON":true,"iot":true,"direct":true,"region":true,"check":true,"memberType":true,"project":true,"directStaticOFF":true,"directVibration":true,"exception":true,"train":true},"equipmentMap":true,"errorData":true,"exception":{}},"manage":{"location":true,"userList":true,"attendance":true,"attendanceTotal":true,"departList":{"search":true},"enclosure":true,"equipmentScreen":true,"financialStatementsAll":true}},"menuid":[133,185,90,177,102,91,89,98,104,135,137,138,105,112,139,196]}},"dataAuthOfRole":{"key":"all_of_depart"},"roleName":"客户管理员","authority":{"product":{"openRecord":true},"financial":{"billPurchase":{},"billRent":{},"bill":true},"systemManager":{"invoice":{}},"vocher":{"vocherList":true},"dashboard":{"analysis":true},"order":{"purchase":{},"rent":{}}},"menuid":[4,5,44,13,14,16,15,20,19,18,25,26],"remark":"可查询本公司所有数据","state":1}]
    }
    wx.redirectTo({
      url: "/pages/equipmentList/equipmentList"
    })
  }else{
    let parameter = {
      userName:inputObj.userName,
      password:inputObj.password
    };

    let auth = Base64.encode(app.globalData.appAccount);
    let authHeader = {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Authorization': 'Basic ' + auth
    };

    const loginInfo = "grant_type=password" +
      "&username=" + inputObj.userName +
      "&password=" + inputObj.password;

    wx.request({
      url: app.globalData.tokenUrl,
      method:'post',
      header: authHeader,
      data: loginInfo,
      success:function(res){
        if(res.statusCode==200 && res.data.access_token){
          app.globalData.loginToken=res.data.access_token;
          console.log('token登录信息');
          console.log(res);

          //获取用户信息
          loginUserName(res.data.userName,parameter,fromRepair,reportForm,reportSend,errorData,errorInside);
        }else{
          Toast.fail(res.data.message);
        }
      },
      fail(){
        Toast.fail('请求数据资源服务错误');
      }
    })
  }
}

//获取用户信息
function loginUserName(userName,parameter,fromRepair,reportForm,reportSend,errorData,errorInside){
  let postParameter={
    userName: userName
  }

  CommonService.getUserByName(postParameter).then(res=>{
    Toast.clear();
    if(res.statusCode==200 && res.data.success==true){
      let user = res.data.data;

      //处理客户权限（客户，厂家，页面里遇到判断这两个类型时用到，其他类型还是用type）
      let multiType=[];
      if(user.departObj[0].multiType){
        multiType=user.departObj[0].multiType;
      }

      let type2Flag=multiType.some(item=>{
        return item==2
      });
      let type4Flag=multiType.some(item=>{
        return item==4
      });

      if(user.departObj[0].type==2 || type2Flag){
        user.typeHandle=2;
      }
      if(user.departObj[0].type==4 || type4Flag){
        user.typeHandle=4;
      }

      console.log('用户登录信息');
      console.log(user);
      app.globalData.userInfo = user;

      let roles = user.roles;
      if (roles.length) {
        //获取用户权限
        getAuthority();

        //将用户名密码存入本地
        try {
          let arrs=[];
          let flag=false;
          let loginInputArr=wx.getStorageSync('loginInputNew');
          
          //比较原存储数组和输入数据
          if(loginInputArr && loginInputArr.length){                
            loginInputArr.forEach(item => {
              if(item.userName!=parameter.userName){
                arrs.push(item);
              }else if((item.userName==parameter.userName) && (item.password!=parameter.password)){
                flag=true;
              }
            });
          }

          if(!flag){
            arrs.push(parameter);
          }
          wx.setStorageSync("loginInputNew",arrs);
          wx.setStorageSync("loginInputLast",parameter);

          //登录版本信息（只适用于天启物联网）
          let editionType = 'oldEdition';
          wx.setStorageSync('editionType', editionType);

        } catch (e) { }

        //如果是从公众号页面跳转来的，登录后转到相应页面（报修，报表）
        if (fromRepair) {
          wx.redirectTo({
            url: "/pages/repairAdd/repairAdd"
          })
        } else if(reportForm){
          wx.redirectTo({
            url: "/pages/reportForm/reportForm"
          })
        } else if(reportSend){
          wx.redirectTo({
            url: "/packageA/pages/reportSend/reportSend"
          })
        }else if(errorData){
          wx.redirectTo({
            url: "/packageA/pages/errorData/errorData"
          })
        }else if(errorInside){
          wx.redirectTo({
            url: "/packageA/pages/errorDataInside/errorDataInside"
          })
        }else{
          //客户跳到个人中心，其他跳到分组
          if (user.departObj[0].type == 4) {
            wx.redirectTo({
              url: "/pages/personalCenter/personalCenter"
            })
          } else {
            wx.redirectTo({
              url: "/pages/equipmentGroup/equipmentGroup"
            })
          }

          //测试用
          // wx.redirectTo({
          //   url: "/packageA/pages/downloadExcel/downloadExcel"
          // })   
        }

      }else {
        Toast.fail('未分配权限，请联系平台管理员');
      }
    }else{
      Toast.fail('用户名或密码错误');
    }
  }).catch((error) => {
  })
}

//获取用户权限
function getAuthority(){
  let user=app.globalData.userInfo;
  let roles=user.roles;
  let roleArr=[];

  roles.forEach(item=>{
    if(item.uiAuthOfRole.iot_weapp){
      roleArr.push(item);
    }
  });

  let authority={};
  roleArr.forEach(item=>{
    DeepAssign(authority,item.uiAuthOfRole.iot_weapp.menu);
  });

  console.log('用户权限');
  console.log(authority);

  app.globalData.authority=authority;
}

//处理角色权限
function DeepAssign(object1,object2) {
  let keys1=Object.keys(object1);
  let keys2=Object.keys(object2);
  let unionkeys = keys1.concat(keys2.filter(v => !keys1.includes(v)));
  unionkeys.forEach(key=>{
    //如果两个对象该字段都有值
    if(object1[key]&&object2[key]){
      //如果对象1为true则无需再向下判断直接等于对象2的值
      if(object1[key]==true){
        object1[key]=object2[key];
      }else if(object2[key]!=true){//如果对象1是个对象类型对象二也是对象类型,则递归调用该方法判断
        DeepAssign(object1[key],object2[key]);
      }
    }else if(object2[key]){
      object1[key]=object2[key];
    }
  })
}

module.exports = {
  tokenLogin: tokenLogin,
  loginUserName: loginUserName
}